package org.texteasy;

import java.util.HashSet;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.Contacts;
import android.provider.Contacts.Groups;
import android.provider.Contacts.People;

public class ContactsAccessorSdk3_4 extends ContactsAccessor {

	private String[] contactsProjection = new String[] {People._ID,People.NAME, People.TYPE, People.NUMBER};
	private String[] groupsProjection = new String[]{Groups._ID, Groups.SYSTEM_ID, Groups.NAME};
	
	@Override
	public Cursor queryContacts(ContentResolver contentResolver, String filter, long selectedGroupId) {
		
		if(filter == null || "".equals(filter.trim())){
			filter = "%";
		}else{
			filter = filter + "%";
		}
		
		String whereClause = People.NUMBER + " is not null and " + People.NAME + 
			" like '" + filter + "'";
		if(selectedGroupId >=0){
			
			whereClause += "AND People." + People._ID + " in " +
				"(SELECT person FROM groups, groupmembership WHERE ((groups._id=groupmembership.group_id OR " +
				"(groups._sync_account=groupmembership.group_sync_account AND groups._sync_id=groupmembership.group_sync_id))) " +
				"AND (GROUPS._ID = " + selectedGroupId + "))";
		}
		
		return contentResolver.query(People.CONTENT_URI, contactsProjection, 
			whereClause, null, People.DEFAULT_SORT_ORDER);
	}

	@Override
	public Cursor queryGroups(ContentResolver contentResolver) {
		return contentResolver.query(Groups.CONTENT_URI, 
			groupsProjection, null, null, Contacts.Groups.DEFAULT_SORT_ORDER);
	}

	
	@Override
	public Cursor queryContactsForPhoneNumbers(ContentResolver contentResolver,
			HashSet<Long> selectedIds) {
		
		StringBuffer buffer = new StringBuffer(" in(");
    	for(Long selectedId: selectedIds){
    		buffer.append(selectedId).
				append(","); 
    	}
		
    	String inStatement = buffer.substring(0, buffer.length() - 1) + ")";
		
		String[] projection = new String[] {People._ID,People.NUMBER};
        
        Uri contacts = People.CONTENT_URI;
        
        return contentResolver.query(contacts, projection, 
    		"PEOPLE." + People._ID + inStatement, null, null);
	}
	
	@Override
	public String getPhoneColumnIndex() {
		return People.NUMBER;
	}
}
